'use client';
import React, { useCallback, useRef } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { getPostList } from './hooks';
import Link from 'next/link';

const PostsClient = () => {
  // 使用 useInfiniteQuery 处理分页数据
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    status,
  } = useInfiniteQuery({
    queryKey: ['posts'],
    queryFn: ({ pageParam = 1 }) => getPostList({ page: pageParam, size: 10 }),
    getNextPageParam: (lastPage, allPages) => {
      // 根据总页数判断是否有下一页
      const totalPages = Math.ceil(100 / 10); // JSONPlaceholder 固定返回100条数据
      const nextPage = allPages.length + 1;
      return nextPage <= totalPages ? nextPage : undefined;
    },
  });

  // 滚动监听：使用 Intersection Observer 检测最后一个元素
  const observer = useRef<IntersectionObserver | null>(null);
  const lastPostElementRef = useCallback(
    (node: HTMLDivElement | null) => {
      if (isFetchingNextPage) return;
      
      // 清除之前的 observer
      if (observer.current) observer.current.disconnect();
      
      // 创建新的 observer
      observer.current = new IntersectionObserver(
        (entries) => {
          if (entries[0].isIntersecting && hasNextPage) {
            fetchNextPage();
          }
        },
        { threshold: 0.5 } // 元素出现 50% 时触发
      );
      
      // 监听最后一个元素
      if (node) observer.current.observe(node);
    },
    [isFetchingNextPage, hasNextPage, fetchNextPage]
  );

  // 处理加载状态
  if (status === 'loading') return <div>Loading initial posts...</div>;
  if (status === 'error') return <div>Failed to fetch posts</div>;

  return (
    <div className="space-y-4">
      <h1>Posts</h1>
      <ul>
        {data?.pages.flatMap((page) =>
          page.map((post) => (
            <li 
              key={post.id}
              ref={page === data.pages[data.pages.length - 1] && 
                  post === page[page.length - 1] ? lastPostElementRef : null}
            >
              <Link href={`/posts/${post.id}`}>
                <h2>{post.id}-{post.title}</h2>
                <p>{post.body}</p>
              </Link>
            </li>
          ))
        )}
      </ul>
      
      {/* 加载更多状态 */}
      {isFetchingNextPage && (
        <div className="text-center py-4">
          <p>Loading more posts...</p>
        </div>
      )}
      
      {/* 没有更多内容 */}
      {!hasNextPage && (
        <div className="text-center py-4 text-gray-500">
          <p>No more posts to load</p>
        </div>
      )}
    </div>
  );
};

export default PostsClient;